<template>
  <el-dialog title="远程控制" :model-value="visible" width="500px" append-to-body @close="handleClose">
    <el-form :model="controlForm" label-width="100px" v-if="data">
      <el-form-item label="设备名称">
        <span>{{ data.deviceName }}</span>
      </el-form-item>
      <el-form-item label="控制指令">
        <el-select v-model="controlForm.command" placeholder="请选择控制指令" style="width: 100%">
          <el-option label="开启设备" value="start" />
          <el-option label="关闭设备" value="stop" />
          <el-option label="重启设备" value="restart" />
          <el-option label="复位设备" value="reset" />
          <el-option label="更新固件" value="update" />
        </el-select>
      </el-form-item>
      <el-form-item label="参数">
        <el-input v-model="controlForm.params" type="textarea" :rows="3" placeholder="请输入控制参数（JSON格式）" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleExecute">执行控制</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

// Props
interface Props {
  visible: boolean
  data: any
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  data: null
})

// Emits
const emit = defineEmits(['update:visible', 'execute', 'cancel'])

// 控制表单
const controlForm = reactive({
  command: '',
  params: ''
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    resetForm()
  }
})

// 执行控制
const handleExecute = () => {
  if (!controlForm.command) {
    ElMessage.warning('请选择控制指令')
    return
  }
  
  emit('execute', {
    deviceId: props.data?.deviceId,
    command: controlForm.command,
    params: controlForm.params
  })
}

// 取消
const handleCancel = () => {
  emit('cancel')
  emit('update:visible', false)
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
}

// 重置表单
const resetForm = () => {
  controlForm.command = ''
  controlForm.params = ''
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>